package com.css.fxfzaqbz.modules.data.repository.impl;


import com.css.fxfzaqbz.constants.YNEnum;
import com.css.fxfzaqbz.modules.data.entity.ActiveFaultData;
import com.css.fxfzaqbz.modules.data.queryParams.ActiveFaultDataQueryParams;
import com.css.fxfzaqbz.modules.data.repository.ActiveFaultDataRepository;
import com.css.fxfzaqbz.util.PlatformObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class ActiveFaultDataRepositoryImpl implements ActiveFaultDataRepository {

    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActiveFaultData updateActiveFaultData(ActiveFaultData activeFaultData) {

        String sql = "update sys_activefaultdata set afd_number = :afdNumber," +
                " afd_name = :afdName, afd_length = :afdLength," +
                " afd_newactivity = :afdNewactivity, afd_status = :afdStatus, " +
                " afd_updatetime = :afdUpdatetime" +
                " where afd_id = '"+activeFaultData.getAfdId()+"'" ;

        SqlParameterSource source = new BeanPropertySqlParameterSource(activeFaultData);
        //拿到新插入的主键值（i）
        KeyHolder keyHolder = new GeneratedKeyHolder();
        namedParameterJdbcTemplate.update(sql,source,keyHolder);
        return activeFaultData;
    }

    @Override
    @Transactional
    public ActiveFaultData saveActiveFaultData(ActiveFaultData activeFaultData) {
        String sql = "insert into sys_activefaultdata values(:afdId,:afdNumber,:afdName,:afdLength,:afdNewactivity,:afdStatus,:afdCreatetime)";

        SqlParameterSource source = new BeanPropertySqlParameterSource(activeFaultData);
        //拿到新插入的主键值（i）
        KeyHolder keyHolder = new GeneratedKeyHolder();
        int i = namedParameterJdbcTemplate.update(sql, source, keyHolder);
        return activeFaultData;
    }

    @Override
    public Page<ActiveFaultData> getAllActiveFaultDataParams(ActiveFaultDataQueryParams queryParams) {
        StringBuilder sql = new StringBuilder(" select  a.* from sys_activefaultdata a ");

        StringBuilder orderSql = new StringBuilder(" order by a.afd_number");

        StringBuilder whereSql = new StringBuilder(" where a.afd_status = '" + YNEnum.Y.toString() + "'");

//        if (!PlatformObjectUtils.isEmpty(queryParams.getElevationBand()) ){
//            whereSql.append(" and e.elevation_band like '%" + queryParams.getElevationBand() + "%'");
//        }
//
//        if (!PlatformObjectUtils.isEmpty(queryParams.getElevationNodatavalue()) ){
//           whereSql.append(" and e.elevation_nodatavalue like '%" + queryParams.getElevationNodatavalue() + "%'");
//        }

        String wholeSql = sql.append(whereSql).append(orderSql).toString();
        List<ActiveFaultData> list = jdbcTemplate.query(wholeSql, new BeanPropertyRowMapper<>(ActiveFaultData.class));
        Pageable pageable = PageRequest.of(queryParams.getCurPage() - 1, queryParams.getPageSize());

        Page<ActiveFaultData> activeFaultData = new PageImpl<>(list, pageable, PlatformObjectUtils.isEmpty(list) ? 0 : list.size());

        return activeFaultData;
    }

    @Override
    public ActiveFaultData getActiveFaultDataById(String id) {
        String sql = "select * from sys_activefaultdata where afd_id = '"+id+"'  and afd_status = '"+YNEnum.Y+"'";
        ActiveFaultData activeFaultData = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(ActiveFaultData.class));
        return activeFaultData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteActiveFaultDatasById(List<String> ids, Timestamp timestamp) {
        String sql = "update sys_activefaultdata set afd_status = '" + YNEnum.N + "' , afd_updatetime = '"+timestamp+"' " + " where afd_id in (:ids)";
        Map map = new HashMap();
        map.put("ids", ids);
        namedParameterJdbcTemplate.update(sql, map);
    }

    @Override
    public List<ActiveFaultData> getAll() {
        return jdbcTemplate.query("select * from sys_activefaultdata where afd_status = '"+YNEnum.Y+"'",new BeanPropertyRowMapper<>(ActiveFaultData.class));
    }

    @Override
    public void importExcel(List<ActiveFaultData> activeFaultData) {
        jdbcTemplate.batchUpdate("insert into sys_activefaultdata (afd_id,afd_number,afd_name,afd_length,afd_newactivity,afd_status,afd_createtime)values(?,?,?,?,?,?,?)", new BatchPreparedStatementSetter() {
            @Override
            public int getBatchSize() {
                return activeFaultData.size();
            }
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ps.setString(1, activeFaultData.get(i).getAfdId());
                ps.setString(2,activeFaultData.get(i).getAfdNumber());
                ps.setString(3,activeFaultData.get(i).getAfdName());
                ps.setString(4,activeFaultData.get(i).getAfdLength());
                ps.setString(5,activeFaultData.get(i).getAfdNewactivity());
                ps.setString(6,activeFaultData.get(i).getAfdStatus());
                java.sql.Date createtime = new java.sql.Date(activeFaultData.get(i).getAfdCreatetime().getTime()) ;
                ps.setDate(7,createtime);
            }
        });
    }

}
